import requests
import time
import hmac
import hashlib
import urllib.parse

# 您的 API 密钥
# API_KEY = 'your_api_key'
# SECRET_KEY = 'your_secret_key'
API_KEY = "oMlYVBgANplqH7XilK0rzJ47r7p1R3MWoywVNBYOGvj5UHYXebQnxZjX9kLpdd5V"
SECRET_KEY = "8587vRjV45QsPPXhlrn3vcBdUwQJFA6HIBqfaVbJO7UqhhqTcVrQCR4GEO6w4OtN"

# 生成签名
def generate_signature(params, secret_key):
    query_string = urllib.parse.urlencode(params)
    signature = hmac.new(secret_key.encode('utf-8'), query_string.encode('utf-8'), hashlib.sha256).hexdigest()
    return signature


def get_binance_server_time():
    """获取币安服务器时间"""
    url = 'https://api.binance.com/api/v3/time'
    response = requests.get(url)
    if response.status_code == 200:
        return response.json()['serverTime']
    else:
        raise Exception("无法获取币安服务器时间")

# 获取利率历史
def get_interest_rate_history(asset, vip_level=0, limit=10):
    base_url = 'https://api.binance.com'
    endpoint = '/sapi/v1/margin/interestRateHistory'

    # 准备参数
    params = {
        'asset': asset,
        'vipLevel': vip_level,
        'limit': limit,
        'timestamp':  get_binance_server_time(),
        'recvWindow': 5000  # 设置接收窗口为5秒
    }

    # 生成签名
    signature = generate_signature(params, SECRET_KEY)
    params['signature'] = signature

    # 准备请求头
    headers = {
        'X-MBX-APIKEY': API_KEY
    }

    # 发送请求
    response = requests.get(base_url + endpoint, params=params, headers=headers)

    if response.status_code == 200:
        return response.json()
    else:
        print(f"Error: {response.status_code}, {response.text}")
        return None


# 使用示例
if __name__ == "__main__":
    # 获取 USDT 的最近利率
    interest_data = get_interest_rate_history('USDT')
    print("USDT Interest Rate History:")
    for record in interest_data:
        print(f"Timestamp: {record['timestamp']}, Rate: {record['dailyInterestRate']}")

    # 获取 BTC 的最近利率
    btc_interest = get_interest_rate_history('BTC')
    print("\nBTC Interest Rate History:")
    for record in btc_interest:
        print(f"Timestamp: {record['timestamp']}, Rate: {record['dailyInterestRate']}")